package com.tgy.cmp;

import com.tgy.Sort;

/**
 * @Author: tgy
 * @Date: 2020-10-13 10:46
 */
public class BubbleSort<E> extends Sort<E> {


    @Override
    protected void sort() {

        optimizeSort();
//        normalSort();
    }

    /**
     * 普通的冒泡排序
     */
    private void normalSort() {

        for (int i = elements.length; i > 1; i--) {

            for (int j = 1; j < i; j++) {

                if (compare(j - 1,j) > 0) {

                    swap(j - 1, j);
                }
            }
        }
    }

    /**
     * 优化之后冒泡排序
     */
    private void optimizeSort() {

        int end;
        for (int i = elements.length - 1; i > 0; i--) {

            end = 1;
            for (int j = 1; j <= i; j++) {

                if (compare(j - 1,j) > 0) {

                    swap(j - 1, j);
                    end = j;
                }
            }
            i = end;
        }

    }


}
